package yzlapi.demo;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {

        var apikey = "";
        var passphrase = "";
        var secret = "";

        System.out.println(get("https://api.yzlkj.com","/api/v1/device/list",
                "",apikey, passphrase, secret));

        System.out.println(get("https://api.yzlkj.com","/api/v1/device/XXXXXX",
                "",apikey, passphrase, secret));
    }

    public static String get(String location, String path, String param, String apikey, String passphrase, String secret) {
        String result = "";
        BufferedReader in = null;
        try {
            String pathAndQuery = path + (param == "" ? "" : "?" + param);
            String urlNameString = location + pathAndQuery;
            URL realUrl = new URL(urlNameString);
            var timeStamp = getUnixTime();
            var sign = sign(timeStamp, pathAndQuery, secret);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("YZL-APIKEY", apikey);
            connection.setRequestProperty("YZL-SIGN", sign);
            connection.setRequestProperty("YZL-TIME", timeStamp);
            connection.setRequestProperty("YZL-PASSPHRASE", passphrase);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }

        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public static String sign(String timeStamp, String PathAndQuery, String secretKey) throws Exception {
        var hash = ha256(timeStamp + "GET" + PathAndQuery, secretKey);
        return base64(hash);
    }

    public static String getUnixTime (){
        Date day= new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.000+08:00");
        return df.format(day);
    }

    public static byte[] ha256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        return array;
    }

    public static  String base64(byte[] data) throws Exception {
        var encoder = Base64.getEncoder().encodeToString(data);
        return encoder;
    }
}
